<!-- 设备IDC -->
<template>
  <basic-container>
    <avue-crud
      v-model="form"
      ref="crud"
      :option="option"
      :table-loading="loading"
      :defaults.sync="defaults"
      :data="data"
      :page.sync="page"
      :permission="permissionList"
      :before-open="beforeOpen"
      :before-close="beforeClose"
      @row-save="rowSave"
      @row-update="addUpdate"
      @row-del="rowDel"
      @search-change="searchChange"
      @search-reset="searchReset"
      @selection-change="selectionChange"
      @current-change="currentChange"
      @size-change="sizeChange"
      @refresh-change="refreshChange"
      @on-load="onLoad"
    >
      <!-- 删除 -->
      <template slot="menuLeft">
        <el-button type="danger" size="small" icon="el-icon-delete" plain @click="handleDelete">删 除 </el-button>
      </template>
      <!-- 锁定 -->
      <template slot-scope="{ type, size, row }" slot="menu">
        <!-- <el-button icon="el-icon-lock" :size="size" :type="type" @click="lock(row.id)">锁定</el-button> -->
        <el-button :disabled="row.status != 1" icon="el-icon-unlock" :size="size" :type="type" @click="unlock(row)">解锁</el-button>
      </template>
      <!-- 锁定状态 -->
      <template slot-scope="{ row }" slot="status">
        <span style="color: rgb(4, 182, 22)" v-if="row.status == 2">已解锁</span>
        <span style="color: red" v-else>已锁定</span>
      </template>
      <!-- 锁定原因 -->
      <template slot-scope="{ row }" slot="lockedReason">
        <span class="idc-record-text" @click="openLockedReasonModal(row.id)">原因</span>
      </template>
      <!-- 锁定对象 -->
      <template slot-scope="{ row }" slot="lockDetail">
        <!-- 产品 -->
        <div v-if="row.lockedType == 'PRODUCT'">
          <span class="lockDetail-cell idc-record-text" @click="openLockedDetailModal(row.id)">产品条码：{{ lockDetailItem(row.lockedObjects) }}</span>
        </div>
        <!-- 物料 -->
        <div v-if="row.lockedType == 'MATERIAL'">
          <span class="lockDetail-cell idc-record-text" @click="openLockedDetailModal(row.id)">物料条码：{{ lockDetailItem(row.lockedObjects) }}</span>
        </div>
        <!-- 工单 -->
        <div v-if="row.lockedType == 'WORKORDER'">
          <span class="lockDetail-cell idc-record-text" @click="openLockedDetailModal(row.id)">工单号：{{ lockDetailWorkerItem(row.lockedObjects) }}</span>
        </div>
        <!-- 工序 -->
        <div v-if="row.lockedType == 'ROUTE'">
          <span class="lockDetail-cell idc-record-text" @click="openLockedDetailModal(row.id)">工序：{{ lockDetailWorkerItem(row.lockedObjects) }}</span>
        </div>
      </template>
      <!-- 解锁说明 -->
      <template slot-scope="{ row }" slot="unlockedRemark">
        <span class="idc-record-text" @click="openUnLockedReasonModal(row.id)">说明</span>
      </template>
      <template slot-scope="{ row }" slot="lockedType">
        <span v-if="row.lockedType == 'WORKORDER'">工单</span>
        <span v-if="row.lockedType == 'ROUTE'">工序</span>
        <span v-if="row.lockedType == 'PRODUCT'">产品</span>
        <span v-if="row.lockedType == 'MATERIAL'">物料</span>
      </template>
    </avue-crud>
    <!-- 弹框 -->
    <common-modal-template ref="commonModalTemplate" :title="tableOption">
      <avue-form v-if="tableOption == '锁定原因' || tableOption == '解锁说明'" :option="commonOption.option" v-model="commonForm" @submit="commonSubmit"></avue-form>
      <div v-else class="codeList">
        <!-- 无序列表 -->
        <template v-if="Array.isArray(codeList)">
          <div class="codeList-ui" v-for="item in codeList" :key="item">
            <i class="el-icon-lock icon" style="color: rgb(128, 134, 149)"></i>
            <span class="codeList-li">{{ item }}</span>
          </div>
        </template>
        <div v-else>
          <li v-if="codeList.workOrderNo">工单号：{{ codeList.workOrderNo }}</li>
          <li v-if="codeList.workorderRouteName">工序：{{ codeList.workorderRouteName }}</li>
        </div>
      </div>
    </common-modal-template>
  </basic-container>
</template>

<script>
import { getList, getDetail, handleUnlock, remove } from '@/api/product/unlock';
import CommonModalTemplate from '@/components/common-modal-template/common-modal-template2.vue';
export default {
  components: {
    CommonModalTemplate
  },
  data() {
    return {
      codeList: [],
      currentRow: null,
      commonOption: {
        option: {
          title: ''
        }
      },
      commonForm: {},
      form: {},
      query: {},
      defaults: {},
      loading: true,
      data: [],
      tableOption: '锁定原因',
      page: {
        pageSize: 20,
        currentPage: 1,
        total: 0
      },
      selectionList: [],
      option: {
        height: 'auto',
        calcHeight: 30,
        tip: false,
        searchShow: true,
        searchMenuSpan: 5,
        border: true,
        index: true,
        indexLabel: '序号',
        addBtn: false,
        viewBtn: false,
        editBtn: false,
        delBtn: true,
        selection: true,
        dialogClickModal: false,
        menu: true,
        menuWidth: 150,
        labelWidth: 120,
        column: [
          {
            label: '锁定类型',
            prop: 'lockedType',
            search: true,
            order: 1,
            slot: true,
            // searchSpan: 4,
            type: 'select',
            dicData: [
              {
                label: '工单',
                value: 'WORKORDER'
              },
              {
                label: '工序',
                value: 'ROUTE'
              },
              {
                label: '产品',
                value: 'PRODUCT'
              },
              {
                label: '物料',
                value: 'MATERIAL'
              }
            ]
          },
          {
            label: '锁定对象',
            prop: 'lockDetail',
            width: 180,
            slot: true
          },
          {
            label: '锁定人',
            prop: 'lockedByName',
            search: true,
            order: 2,
            rules: [
              {
                required: true,
                message: '请输入锁定人'
              }
            ],
            order: 1
          },
          {
            label: '锁定时间',
            prop: 'lockedTime',
            rules: [
              {
                required: true,
                message: '请输入锁定时间'
              }
            ]
          },
          {
            label: '锁定原因',
            prop: 'lockedReason',
            slot: true
          },

          {
            label: '锁定状态',
            prop: 'status',
            slot: true
          },
          {
            label: '解锁人',
            prop: 'unlockedByName'
          },
          {
            label: '解锁时间',
            prop: 'unlockedTime',
            type: 'datetime',
            format: 'yyyy-MM-dd HH:mm:ss',
            valueFormat: 'yyyy-MM-dd HH:mm:ss'
          },
          {
            label: '解锁说明',
            prop: 'unlockedRemark',
            slot: true
          },
          {
            label: '解锁时长(H)',
            prop: 'duration'
          }
        ]
      }
    };
  },
  computed: {
    ids() {
      let ids = [];
      this.selectionList.forEach((ele) => {
        ids.push(ele.id);
      });
      return ids.join(',');
    },
    // 锁定对象(产品，物料)
    lockDetailItem(item) {
      return (item) => {
        let content = JSON.parse(item || '[]').join(','),
          strLen = content.length;
        if (strLen > 15) {
          content = content.substr(0, 15) + '...';
        }
        return content;
      };
    },
    // 锁定对象(工单，工序)
    lockDetailWorkerItem(item) {
      return (item) => {
        // 工单
        let data = JSON.parse(item || '{}');
        if (!data.workorderRouteId) {
          let content = data.workOrderNo,
            strLen = content.length;
          if (strLen > 15) {
            content = content.substr(0, 15) + '...';
          }
          return content;
        } else {
          // 工序
          if (data.workorderRouteName) {
            let content = data.workorderRouteName,
              strLen = content.length;
            if (strLen > 15) {
              content = content.substr(0, 15) + '...';
            }
            return content;
          }
        }
      };
    }
  },
  methods: {
    rowDel(row) {
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          return remove(row.id);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
        });
    },
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning('请选择至少一条数据');
        return;
      }
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          return remove(this.ids);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          this.$refs.crud.toggleSelection();
        });
    },
    lock() {
      this.$confirm('确定将选择数据锁定?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          return remove(this.ids);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          this.$refs.crud.toggleSelection();
        });
    },
    unlock(row) {
      if (this.commonForm) {
        this.commonForm.unlockedRemark = '';
      }
      this.currentRow = JSON.parse(JSON.stringify(row));
      this.tableOption = '解锁说明';
      this.commonOption.option = {
        menuPosition: 'right', //表单菜单按钮的排列方式
        column: [
          {
            label: '解锁说明',
            prop: 'unlockedRemark',
            type: 'textarea',
            minRows: 3,
            span: 24,
            maxRows: 3,
            rules: [
              {
                required: true,
                message: '请输入解锁说明',
                trigger: 'blur'
              }
            ]
          }
        ]
      };
      this.$refs.commonModalTemplate.showModal();
    },
    // 解锁确定
    commonSubmit(form, done) {
      this.currentRow.unlockedRemark = form.unlockedRemark;
      handleUnlock(this.currentRow)
        .then((res) => {
          console.log(res);
          this.onLoad(this.page);
          this.$refs.commonModalTemplate.hideModal();
          this.$message({
            type: 'success',
            message: '解锁成功!'
          });
          done();
        })
        .catch((err) => {
          console.log(err);
          done();
        });
    },
    beforeOpen(done, type) {
      if (['add', 'edit', 'view'].includes(type)) {
        this.defaults.histroyIDC.display = false;
      }
      done();
    },
    beforeClose(done, type) {
      done();
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },

    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    onLoad(page, params = {}) {
      this.loading = true;
      getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then((res) => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.loading = false;
        this.selectionClear();
      });
    },
    // 锁定原因弹框 配置
    openLockedReasonModal(id) {
      this.tableOption = '锁定原因';
      this.commonOption.option = {
        title: '锁定原因',
        submitBtn: false,
        emptyBtn: false,
        column: [
          {
            label: '锁定原因',
            prop: 'lockedReason',
            type: 'textarea',
            minRows: 3,
            span: 24,
            disabled: true,
            maxRows: 3
          }
        ]
      };
      this.$refs.commonModalTemplate.showModal();
      getDetail(id)
        .then((res) => {
          if (res && res.status == 200) {
            let data = res.data.data;
            this.commonForm.lockedReason = data.lockedReason;
            console.log(data);
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    // 锁定详情弹框 配置
    openLockedDetailModal(id) {
      getDetail(id)
        .then((res) => {
          if (res && res.status == 200) {
            let data = res.data.data;
            let lockedObjects = null;
            this.tableOption = '锁定对象';
            switch (data.lockedType) {
              case 'PRODUCT':
                this.tableOption = '锁定对象（产品条码）';
                break;
              case 'MATERIAL':
                this.tableOption = '锁定对象（物料条码）';
                break;
              case 'WORKORDER':
                this.tableOption = '锁定对象（工单号）';
                break;
              case 'ROUTE':
                this.tableOption = '锁定对象（工序）';
                break;
              default:
                break;
            }
            if (data.lockedType == 'PRODUCT' || data.lockedType == 'MATERIAL') {
              this.codeList = JSON.parse(data.lockedObjects || '[]');
            } else {
              this.codeList = JSON.parse(data.lockedObjects || '{}');
            }
            console.log(this.codeList);
            this.$refs.commonModalTemplate.showModal();
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    // 解锁说明弹框 配置
    openUnLockedReasonModal(id) {
      this.tableOption = '解锁说明';
      this.commonOption.option = {
        title: '解锁说明',
        submitBtn: false,
        emptyBtn: false,
        column: [
          {
            label: '解锁说明',
            prop: 'unlockedRemark',
            type: 'textarea',
            minRows: 3,
            span: 24,
            disabled: true,
            maxRows: 3
          }
        ]
      };
      this.$refs.commonModalTemplate.showModal();
      getDetail(id)
        .then((res) => {
          if (res && res.status == 200) {
            let data = res.data.data;
            this.commonForm.unlockedRemark = data.unlockedRemark;
          }
        })
        .catch((err) => {
          console.log(err);
        });
    }
  }
};
</script>

<style lang="scss" scoped>
.idc-record-text {
  color: #409eff;
  cursor: pointer;
}
.lockDetail-cell {
  cursor: pointer;
}
.codeList {
  max-height: 400px;
  overflow: auto;
  .codeList-ui {
    .icon {
      margin-right: 8px;
    }
    .codeList-li {
      color: #666;
      font-size: 14px;
    }
  }
}
</style>
